'use strict';
import {observable, action, computed, runInAction, toJS} from 'mobx'
import BaseStore from './BaseStore'
import Constants from '../config/Constants'

class LoginStore extends BaseStore {

    constructor(params) {
        super(params);
        global.token = '';
        global.secretKey = '';
        // global.secretKey = ''
        this.userInfo = {}
    }

    @observable userInfo;

    @computed
    get getUserInfo() {
        return toJS(this.userInfo);
    }

    @action
    getUserData = async (userId) => {
        const data = { member_id: userId };
        const dataSource = await this.postRequest(ServicesApi.GET_USER_INFO, data);
        // console.log('获取用户信息返回-------------->', dataSource);
        runInAction(() => {
            if (dataSource.code === StatusCode.SUCCESS_CODE) {
                this.saveUserInfo(dataSource.data)
            } else {

            }
        });
        return dataSource
    };

    @action
    gotoLogin = async (url, data) => {
        const result = await this.postRequest(url, data);
        runInAction(() => {
            if (result.code === StatusCode.SUCCESS_CODE) {
                this.getUserData(result.data.user_id)
            }
        });
        return result
    };

    @action
    thirdLogin = async (url,data) => {
        const result = await this.postRequest(url, data);
        runInAction(() => {
            if (result.code === StatusCode.SUCCESS_CODE && result.data.user_phone) { //手机号存在，说明已绑定，只有这时才去持久化存储
                this.getUserData(result.data.user_id)
            }
        });
        return result
    };

    @action
    saveUserInfo = (userInfo) => {
        // if (userInfo.user_token && userInfo.user_id) {
        //     global.token = userInfo.user_token
        //     global.secretKey = userInfo.user_id
        // }

        if ( userInfo.user_id) {
            global.secretKey = userInfo.user_id
        }
        this.userInfo = userInfo
        StorageManager.save(Constants.USER_INFO_KEY, userInfo)
        // StorageManager.save(Constants.USER_INFO_KEY, {isLogin:true})
    }

    @action
    cleanUserInfo = () => {
        global.token = ''
        global.secretKey = ''
        this.userInfo = {}
        StorageManager.remove(Constants.USER_INFO_KEY)
    }

}

export default LoginStore